package com.hanbang.cxgz_2.view.widget.media;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.utils.ui.ToastUtils;
import com.hanbang.cxgz_2.utils.ui.UiUtils;

import java.io.IOException;

import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_AUTO_COMPLETE;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_NORMAL;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PAUSE;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PLAYING;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PREPAREING;

/**
 * Created by Administrator on 2016/4/20.
 * likun
 */
public class MusicPlayView extends LinearLayout {

    /**
     * public static final int CURRENT_STATE_NORMAL = 0;
     * public static final int CURRENT_STATE_PREPAREING = 1;
     * public static final int CURRENT_STATE_PLAYING = 2;
     * public static final int CURRENT_STATE_PLAYING_BUFFERING_START = 3;
     * public static final int CURRENT_STATE_PAUSE = 5;
     * public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
     * public static final int CURRENT_STATE_ERROR = 7;
     */
    private MediaPlayer mediaPlayer;
    private DeleteOnClick deleteOnClick;
    private String filePath;
    private int state = VideoPlayView.CURRENT_STATE_NORMAL;

    public MusicPlayView(Context context) {
        this(context, null);
    }

    public MusicPlayView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MusicPlayView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        intiView();
    }

    private void intiView() {
        View v = UiUtils.getInflaterView(getContext(), R.layout.music_play, this, true);
        if (!isInEditMode()) {
//            ViewUtils.inject(this, v);

            playIv = (ImageView) v.findViewById(R.id.play);
            playIv.setImageResource(R.drawable.material_video_play_play);
            deleteIv = (ImageView) v.findViewById(R.id.delete);
            seekBar = (SeekBar) v.findViewById(R.id.seekBar);
            timeTv = (TextView) v.findViewById(R.id.time);
            seekBar.setThumb(getResources().getDrawable(R.drawable.video_play_seek_thumb));
            seekBar.setProgressDrawable(getResources().getDrawable(R.drawable.video_play_seek_progress));

            setListener();
        }
    }


    private class TimeRunable implements Runnable {
        boolean isPause = false;

        public void setPause() {
            isPause = true;
        }


        @Override
        public void run() {
            if (!isPause) {

                timeTv.setText(getTime());
                seekBar.setProgress(getPostion());
                timeTv.postDelayed(timeRunable, 100);
            }
        }
    }

    TimeRunable timeRunable = null;

    private void init() {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {//播出完毕事件
            @Override
            public void onCompletion(MediaPlayer arg0) {
                complete();
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {// 错误处理事件
            @Override
            public boolean onError(MediaPlayer player, int arg1, int arg2) {
                mediaPlayer.reset();
                state = VideoPlayView.CURRENT_STATE_ERROR;
                ToastUtils.show(getContext(), "播放失败", 1);
                if (timeRunable != null) {
                    timeRunable.setPause();
                }
                return false;
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
//                play();
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 是用户触摸的
                if (fromUser) {
                    seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mediaPlayer.setVolume(1.0f, 1.0f);
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
        prepare();//取消设置路径后就播放
    }

    public void prepare() {
        if (TextUtils.isEmpty(filePath)) return;


        init();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.reset();//重置为初始状态
        }
        try {

            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepareAsync();//缓冲
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            state = CURRENT_STATE_PREPAREING;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

    }

    /*
         * 快进或快退baifenbi（0-1000）
         */
    public void seekTo(int baifenbi) {
        if (state == CURRENT_STATE_PLAYING || state == CURRENT_STATE_PAUSE) {
            float ms = mediaPlayer.getDuration();// ms
            mediaPlayer.seekTo((int) Math.rint(ms * baifenbi / 1000.0));
        }
    }


    /**
     * 播放音乐
     */
    private void play() {
        if (state == CURRENT_STATE_PAUSE || state == CURRENT_STATE_PREPAREING) {
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            mediaPlayer.start();//播放
            state = CURRENT_STATE_PLAYING;
            playIv.setImageResource(R.drawable.material_video_play_pause);
            timeTv.postDelayed(timeRunable = new TimeRunable(), 100);
        }
    }

    /**
     * 暂停音乐
     */
    public void pause() {

        if (state == CURRENT_STATE_PLAYING && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//展厅
            state = CURRENT_STATE_PAUSE;
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            playIv.setImageResource(R.drawable.material_video_play_play);
            if (timeRunable != null) {
                timeRunable.setPause();
            }
        }
    }

    /**
     * 作者　　: 李坤
     * 创建时间: 2016/9/3 15:30
     * <p>
     * 方法功能：
     */

    public void stop() {
        if (mediaPlayer.isPlaying()) {
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            mediaPlayer.stop();
        }
    }

    /**
     * 播放结束
     */
    private void complete() {
        AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        if (timeRunable != null) {
            timeRunable.setPause();
        }
        mediaPlayer.release();
        state = CURRENT_STATE_AUTO_COMPLETE;
        playIv.setImageResource(R.drawable.material_video_play_play);
        seekBar.setProgress(0);
        timeTv.setText("00:00 / 00:00");
    }

    public AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            //AUDIOFOCUS_GAIN, AUDIOFOCUS_LOSS, AUDIOFOCUS_LOSS_TRANSIENT and AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK.
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN://用于指示音频焦点的增益，或音频设备的请求，持续时间未知。
                    play();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS://用来表示持续时间未知的音频焦点损失。
                    stop();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://用于指示音频重点短暂丧失。
                    pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    //用于指示音频重点短暂丧失在音频焦点，如果它想继续打球可以降低其输出音量的失败者（也被称为“回避”），作为新的焦点所有者不需要别人沉默。
                    break;
            }
        }
    };

    /**
     * 删除按钮点击
     */
//    @OnClick(R.id.delete)
//    private void deleteOnClick(View v) {
//        if (deleteOnClick != null) {
//            deleteOnClick.onDelete();
//        }
//    }

    /**
     * 播放按钮点击
     */
//    @OnClick(R.id.play)
//    private void playOnClick(View v) {
//        if (state == State.PLAY) {//播放中
//            pause();
//        } else if (state == State.PAUSE) {//暂停中
//            play();
//        } else if ((state != State.PREPAR)) {//
//            prepare();
//        }
//    }
    private void setListener() {

        //删除按钮点击
        deleteIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (deleteOnClick != null) {
                    deleteOnClick.onDelete();
                }
            }
        });

        //播放按钮点击
        playIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (state == CURRENT_STATE_PLAYING) {//播放中
                    pause();
                } else if (state == CURRENT_STATE_PAUSE || state == CURRENT_STATE_PREPAREING) {//暂停中  或者 准备好了
                    play();
                } else if ((state != CURRENT_STATE_NORMAL)) {//
                    prepare();
                }
            }
        });


    }

    /**
     * 释放资源, 外部调用
     */
    public void release() {
        if (state != CURRENT_STATE_AUTO_COMPLETE) {
            state = CURRENT_STATE_AUTO_COMPLETE;
            if (timeRunable != null)
                timeRunable.setPause();
            try {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    if (mediaPlayer != null) {
                        mediaPlayer.release();
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 设置是否显示删除按钮
     */

    public void setDeleteVisibility(int visibility) {
        deleteIv.setVisibility(visibility);
    }

    public interface DeleteOnClick {
        void onDelete();
    }

    public void setDeleteOnClick(DeleteOnClick deleteOnClick) {
        this.deleteOnClick = deleteOnClick;
    }

    private String getTime() {
        if (state == CURRENT_STATE_PLAYING || state == CURRENT_STATE_PAUSE) {
            int allTime = mediaPlayer.getDuration();//ms
            int currTime = mediaPlayer.getCurrentPosition();//ms
            return String.format("%02d:%02d / %02d:%02d", (int) (currTime / 1000.0) / 60, (int) (currTime / 1000.0) % 60, (int) (allTime / 1000.0) / 60, (int) (allTime / 1000.0) % 60);
        } else {
            return "00:00 / 00:00";
        }
    }

    /**
     * 0-1000
     */
    private int getPostion() {
        /**
         * 0-1000
         */
        if (state == CURRENT_STATE_PLAYING || state == CURRENT_STATE_PAUSE) {
            int allTime = mediaPlayer.getDuration();//ms
            int curr = mediaPlayer.getCurrentPosition();

            int p = (int) ((curr / (allTime * 1.0)) * 1000.0);
            if (p <= 0) {
                return 0;
            } else if (p > 1000) {
                return 1000;
            } else {
                return p;
            }
        } else {
            return 0;
        }
    }

    private ImageView playIv;
    private ImageView deleteIv;
    private SeekBar seekBar;
    private TextView timeTv;
}
